import { registerDecorator, ValidationOptions } from 'class-validator';
import { AccountErrorKey } from '../constants/user.constant';
import { StringUtil } from '../utils/string.util';
import { ResponseMsgKey } from '../constants/api-response.constant';
import { DictType } from 'src/module/sys/dict/entities/dict-type.entity';

/**
 * 校验密码强度
 * @param level 强度等级 default 1
 * @param validationOptions
 * @returns
 *  5: 包含大小写字母，数字及特殊字符且字符长度大于8位
 *  4: 包含大小写字母，数字
 *  3: 包含字母，数字且字符长度大于8位
 *  2: 字符长度大于8位
 *  1: 字符长度小于8位
 */
export function CheckPasswordStrength(
  level: number = 1,
  validationOptions?: ValidationOptions,
) {
  return function (object: any, propertyName: string) {
    registerDecorator({
      name: 'checkPasswordStrength',
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      validator: {
        defaultMessage(): string {
          return AccountErrorKey.PASSWORD_STRENGTH;
        },
        validate(value: any) {
          const strengthLevel = StringUtil.checkPasswordStrength(value);
          if (strengthLevel < level) return false;

          return true;
        },
      },
    });
  };
}

/**
 * 校验传入参数是否是字典项值
 * @param code 字典类型code
 * @param validationOptions
 * @returns
 */
export function IsDictItemValue(
  code: string,
  validationOptions?: ValidationOptions,
) {
  return function (object: any, propertyName: string) {
    registerDecorator({
      name: 'isDictItemValue',
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      validator: {
        defaultMessage(): string {
          return ResponseMsgKey.PARAM_ERROR;
        },
        validate(value: string) {
          return DictType.existsBy({
            code: code,
            items: {
              value: value,
            },
          });
        },
      },
    });
  };
}
